<template>
  <div class="rule-config-container">
    <!-- 搜索表单 -->
    <a-card :bordered="false" class="search-card">
      <div class="search-form-wrapper">
        <a-form layout="inline" :form="form" @submit="handleSearch" class="search-form">
          <!-- 基础筛选项（始终显示） -->
          <div class="form-row" :class="{ 'single-row': !needToggle }">
            <a-form-item label="" class="form-item">
              <a-input v-decorator="['ruleCode']" placeholder="请输入规则标识" :style="{ width: '180px' }" allowClear />
            </a-form-item>
            <a-form-item label="" class="form-item">
              <a-input v-decorator="['ruleName']" placeholder="请输入规则名称" :style="{ width: '180px' }" allowClear />
            </a-form-item>
            <a-form-item label="" class="form-item">
              <a-select v-decorator="['workflowCode']" placeholder="请选择关联决策流" :style="{ width: '180px' }" allowClear
                showSearch>
                <a-select-option v-for="option in workflowOptions" :key="option.workflowCode"
                  :value="option.workflowCode">
                  {{ option.workflowName }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <!-- 扩展筛选项（当不需要切换时直接显示在第一行） -->
            <template v-if="!needToggle">
              <a-form-item label="" class="form-item">
                <a-select v-decorator="['nodeType']" placeholder="请选择节点类型" :style="{ width: '180px' }" allowClear
                  showSearch @change="handleNodeTypeChange">
                  <a-select-option v-for="option in nodeTypeOptions" :key="option.nodeType" :value="option.nodeType">
                    {{ option.nodeName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="" class="form-item">
                <a-select v-decorator="['nodeId']" placeholder="请选择关联节点" :style="{ width: '180px' }" allowClear
                  showSearch>
                  <a-select-option v-for="option in nodeOptions" :key="option.nodeId" :value="option.nodeId">
                    {{ option.nodeName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </template>

            <!-- 操作按钮 -->
            <a-form-item label="" class="form-item action-buttons">
              <a-button icon="search" type="primary" html-type="submit" :loading="loading">
                搜索
              </a-button>
              <a-button style="margin-left: 8px" @click="handleReset">
                重置
              </a-button>
              <a-button icon="plus" type="primary" style="margin-left: 8px" @click="handleAdd"
                v-if="$hasPermission('add')">
                新增
              </a-button>
              <!-- 展开收起按钮 -->
              <a-button type="link" @click="toggleExpanded" class="expand-btn" v-show="needToggle">
                {{ expanded ? '收起' : '展开' }}
                <a-icon :type="expanded ? 'up' : 'down'" />
              </a-button>
            </a-form-item>
          </div>

          <!-- 扩展筛选项（仅在需要切换且展开时显示） -->
          <div class="form-row expanded-row" v-if="needToggle" v-show="expanded">
            <a-form-item label="" class="form-item">
              <a-select v-decorator="['nodeType']" placeholder="请选择节点类型" :style="{ width: '180px' }" allowClear
                showSearch @change="handleNodeTypeChange">
                <a-select-option v-for="option in nodeTypeOptions" :key="option.nodeType" :value="option.nodeType">
                  {{ option.nodeName }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="" class="form-item">
              <a-select v-decorator="['nodeId']" placeholder="请选择关联节点" :style="{ width: '180px' }" allowClear
                showSearch>
                <a-select-option v-for="option in nodeOptions" :key="option.nodeId" :value="option.nodeId">
                  {{ option.nodeName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </div>
        </a-form>
      </div>
    </a-card>

    <!-- 数据表格 -->
    <a-card :bordered="false" class="table-card">
      <div class="table-page-search-wrapper">
        <a-table :columns="columns" :data-source="dataSource" :pagination="pagination" :loading="loading"
          :scroll="{ x: 1200 }" row-key="id" @change="handleTableChange">
          <!-- 规则标识列 -->
          <template slot="ruleCode" slot-scope="text">
            <span>{{ text || '--' }}</span>
          </template>

          <!-- 规则名称列 -->
          <template slot="ruleName" slot-scope="text">
            <span>{{ text || '--' }}</span>
          </template>

          <!-- 关联决策流列 -->
          <template slot="workflowName" slot-scope="text">
            <span>{{ text || '--' }}</span>
          </template>

          <!-- 关联节点列 -->
          <template slot="nodeName" slot-scope="text">
            <span>{{ text || '--' }}</span>
          </template>

          <!-- 引用指标列 -->
          <template slot="quoteIndices" slot-scope="text, record">
            <div class="quote-indices-list">
              <div v-for="(item, index) in record.quoteIndices" :key="index" class="quote-indices-item">
                <span class="item-index">{{ index + 1 }}、</span>
                <span class="index-name">{{ item.indexName }}:</span>
                <span class="operator">{{ item.operator }}</span>
                <span class="threshold">{{ item.threshold }}</span>
              </div>
            </div>
          </template>

          <!-- 状态列 -->
          <template slot="status" slot-scope="text, record">
            <a-switch :checked="text === 1" :loading="record.statusLoading"
              @change="(checked) => handleStatusChange(record, checked)" />
          </template>

          <!-- 创建人列 -->
          <template slot="createBy" slot-scope="text">
            <span>{{ text || '--' }}</span>
          </template>

          <!-- 创建时间列 -->
          <template slot="gmtCreate" slot-scope="text">
            <span>{{ text || '--' }}</span>
          </template>

          <!-- 操作列 -->
          <template slot="action" slot-scope="text, record">
            <a @click="handleView(record)" v-if="$hasPermission('look')">查看</a>
            <a-divider type="vertical" />
            <a @click="handleEdit(record)" v-if="$hasPermission('modify')">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleCopy(record)" v-if="$hasPermission('copy')">复制</a>
            <a-divider type="vertical" />
            <a @click="handleDelete(record)" style="color: #ff4d4f" v-if="$hasPermission('delete')">删除</a>
          </template>
        </a-table>
      </div>
    </a-card>
  </div>
</template>

<script>
import { alarmRulePage, relationNodeConfig, relationWorkflow, alarmRuleUpdateStatus, alarmRuleDelete } from '@/api/ruleConfig'

export default {
  name: 'RuleConfig',
  beforeRouteEnter(to, from, next) {
    if (from.path === '/403') {
      window.location.reload()
      return
    }
    next((vm) => {
      if (!vm.$hasPermission('query')) {
        vm.$router.push({ path: '/403' })
      }
    })
  },
  data() {
    return {
      form: this.$form.createForm(this),
      loading: false,
      expanded: false, // 控制筛选器展开收起状态
      needToggle: false, // 是否需要显示展开收起按钮
      containerWidth: 0, // 容器宽度
      dataSource: [],
      nodeTypeOptions: [],
      nodeOptions: [], // 关联节点选项
      selectedNodeType: '', // 当前选中的节点类型
      nodeConfigData: [], // 完整的节点配置数据
      workflowOptions: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total, range) => `共 ${total} 条记录，第 ${range[0]}-${range[1]} 条`
      },
      queryParams: {
        curPage: 1,
        pageSize: 10
      },
      columns: [
        {
          title: '规则标识',
          dataIndex: 'ruleCode',
          key: 'ruleCode',
          width: 120,
          scopedSlots: { customRender: 'ruleCode' }
        },
        {
          title: '规则名称',
          dataIndex: 'ruleName',
          key: 'ruleName',
          width: 150,
          scopedSlots: { customRender: 'ruleName' }
        },
        {
          title: '关联决策流',
          dataIndex: 'workflowName',
          key: 'workflowName',
          width: 120,
          scopedSlots: { customRender: 'workflowName' }
        },
        {
          title: '关联节点',
          dataIndex: 'nodeName',
          key: 'nodeName',
          width: 100,
          scopedSlots: { customRender: 'nodeName' }
        },
        {
          title: '引用指标',
          dataIndex: 'quoteIndices',
          key: 'quoteIndices',
          width: 300,
          scopedSlots: { customRender: 'quoteIndices' }
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          width: 80,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '创建人',
          dataIndex: 'createBy',
          key: 'createBy',
          width: 100,
          scopedSlots: { customRender: 'createBy' }
        },
        {
          title: '创建时间',
          dataIndex: 'gmtCreate',
          key: 'gmtCreate',
          width: 160,
          scopedSlots: { customRender: 'gmtCreate' }
        },
        {
          title: '操作',
          key: 'action',
          width: 230,
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },
  mounted() {
    this.fetchNodeTypeOptions()
    this.fetchWorkflowOptions()
    this.fetchData()
    this.checkContainerWidth()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    // 获取数据
    async fetchData() {
      this.loading = true
      try {
        const params = {
          curPage: this.queryParams.curPage,
          pageSize: this.queryParams.pageSize
        }

        // 添加可选参数
        if (this.queryParams.ruleCode) {
          params.ruleCode = this.queryParams.ruleCode
        }
        if (this.queryParams.ruleName) {
          params.ruleName = this.queryParams.ruleName
        }
        if (this.queryParams.nodeType) {
          params.nodeType = this.queryParams.nodeType
        }
        if (this.queryParams.nodeId) {
          params.nodeId = this.queryParams.nodeId
        }
        if (this.queryParams.workflowCode) {
          params.workflowCode = this.queryParams.workflowCode
        }

        const response = await alarmRulePage(params)
        if (response.success) {
          this.dataSource = response.data.contents
          this.pagination.total = response.data.total
          this.pagination.current = response.data.curPage
        } else {
          this.$message.error(response.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取规则配置数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.queryParams = {
            curPage: 1,
            pageSize: this.pagination.pageSize,
            ...values
          }
          this.pagination.current = 1
          this.fetchData()
        }
      })
    },

    // 重置
    handleReset() {
      this.form.resetFields()
      this.queryParams = {
        curPage: 1,
        pageSize: this.pagination.pageSize
      }
      this.pagination.current = 1
      this.fetchData()
    },

    // 表格变化
    handleTableChange(pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.queryParams.curPage = pagination.current
      this.queryParams.pageSize = pagination.pageSize
      this.fetchData()
    },

    // 新增规则
    handleAdd() {
      this.$router.push({
        path: '/heimdallr/ruleConfig/detail',
        query: {
          type: 1
        }
      })
    },

    // 查看详情
    handleView(record) {
      this.$router.push({
        path: '/heimdallr/ruleConfig/detail',
        query: {
          id: record.id,
          type: 3
        }
      })
    },

    // 编辑规则
    handleEdit(record) {
      this.$router.push({
        path: '/heimdallr/ruleConfig/detail',
        query: {
          id: record.id,
          type: 2
        }
      })
    },

    // 复制规则
    handleCopy(record) {
      this.$router.push({
        path: '/heimdallr/ruleConfig/detail',
        query: {
          id: record.id,
          type: 1
        }
      })
    },

    // 删除规则
    handleDelete(record) {
      this.$confirm({
        title: '确认删除',
        content: `确定要删除规则"${record.ruleName}"吗？`,
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          try {
            const formData = new FormData()
            formData.append('id', record.id)

            const response = await alarmRuleDelete(formData)
            if (response.success) {
              this.$message.success('删除成功')
              this.fetchData() // 重新加载数据
            } else {
              this.$message.error(response.message || '删除失败')
            }
          } catch (error) {
            console.error('删除规则失败:', error)
            this.$message.error('删除失败')
          }
        }
      })
    },

    // 获取节点类型选项
    async fetchNodeTypeOptions() {
      try {
        const response = await relationNodeConfig()
        if (response.success && response.data) {
          // 保存完整的节点配置数据
          this.nodeConfigData = response.data
          // 提取第一级的nodeType和nodeName
          this.nodeTypeOptions = response.data.map(item => ({
            nodeType: item.nodeType,
            nodeName: item.nodeName
          }))
        } else {
          console.error('获取节点类型失败:', response.message)
        }
      } catch (error) {
        console.error('获取节点类型选项失败:', error)
      }
    },

    // 处理节点类型变化
    handleNodeTypeChange(nodeType) {
      this.selectedNodeType = nodeType
      // 清空关联节点选择
      this.form.setFieldsValue({ nodeId: undefined })

      if (nodeType) {
        // 根据选中的节点类型找到对应的关联节点列表
        const selectedConfig = this.nodeConfigData.find(item => item.nodeType === nodeType)
        if (selectedConfig && selectedConfig.nodeList) {
          this.nodeOptions = selectedConfig.nodeList
        } else {
          this.nodeOptions = []
        }
      } else {
        this.nodeOptions = []
      }
    },

    // 获取关联决策流选项
    async fetchWorkflowOptions() {
      try {
        const response = await relationWorkflow()
        if (response.success && response.data) {
          // 提取workflowCode和workflowName
          this.workflowOptions = response.data.map(item => ({
            workflowCode: item.workflowCode,
            workflowName: item.workflowName
          }))
        } else {
          console.error('获取关联决策流失败:', response.message)
        }
      } catch (error) {
        console.error('获取关联决策流选项失败:', error)
      }
    },

    // 切换筛选器展开收起状态
    toggleExpanded() {
      this.expanded = !this.expanded
    },

    // 处理窗口大小变化
    handleResize() {
      this.checkContainerWidth()
    },

    // 检查容器宽度，决定是否需要展开收起功能
    checkContainerWidth() {
      this.$nextTick(() => {
        const container = this.$el.querySelector('.search-form')
        if (container) {
          this.containerWidth = container.offsetWidth

          // 临时设置为不需要切换模式来测量所有项目的宽度
          const originalNeedToggle = this.needToggle
          this.needToggle = false

          this.$nextTick(() => {
            // 计算所有筛选项在一行时的总宽度
            const allItems = container.querySelectorAll('.form-row:first-child .form-item')
            let totalWidth = 0
            allItems.forEach(item => {
              totalWidth += item.offsetWidth + 16 // 16px是margin-right
            })

            const availableWidth = this.containerWidth - 40 // 预留一些边距

            if (totalWidth <= availableWidth) {
              // 宽度足够，不需要展开收起功能，所有项目一行显示
              this.needToggle = false
              this.expanded = true
            } else {
              // 宽度不足，需要展开收起功能
              this.needToggle = true
              // 默认收起状态
              this.expanded = false
            }
          })
        }
      })
    },

    // 状态切换
    async handleStatusChange(record, checked) {
      // 设置当前行的loading状态
      this.$set(record, 'statusLoading', true)

      try {
        const status = checked ? 1 : 2 // 1: 启用, 2: 禁用
        const response = await alarmRuleUpdateStatus({
          id: record.id,
          status: status
        })

        if (response.success) {
          // 更新本地状态
          record.status = status === 1 ? 1 : 0 // API使用1/2，显示使用1/0
          this.$message.success(checked ? '启用成功' : '禁用成功')
        } else {
          this.$message.error(response.message || '状态更新失败')
        }
      } catch (error) {
        console.error('状态更新失败:', error)
        this.$message.error('状态更新失败')
      } finally {
        // 清除loading状态
        this.$set(record, 'statusLoading', false)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.rule-config-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;

  .search-card {
    margin-bottom: 24px;

    .search-form-wrapper {
      .search-form {
        .form-row {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          margin-bottom: 16px;

          &:last-child {
            margin-bottom: 0;
          }

          .form-item {
            margin-right: 16px;
            margin-bottom: 8px;

            &.action-buttons {
              display: flex;
              align-items: center;

              .expand-btn {
                margin-left: 16px;
                padding: 4px 8px;
                color: #1890ff;

                &:hover {
                  color: #40a9ff;
                }
              }
            }
          }

          // 当不需要切换时，第一行和扩展行合并为一行
          &:first-child {
            &.single-row {
              .form-item {
                flex-shrink: 0;
              }
            }
          }
        }

        .expanded-row {
          border-top: 1px solid #f0f0f0;
          padding-top: 16px;
          margin-top: 8px;
          animation: slideDown 0.3s ease-in-out;

          // 当不需要切换时，移除边框和动画，并与第一行合并显示
          &.no-toggle {
            border-top: none;
            padding-top: 0;
            margin-top: -16px; // 负边距使其与第一行合并
            margin-left: 0;
            animation: none;

            .form-item {
              display: inline-flex;
            }
          }
        }
      }
    }
  }

  .table-card {
    .quote-indices-list {
      .quote-indices-item {
        display: flex;
        align-items: center;
        margin-bottom: 4px;
        font-size: 12px;

        .item-index {
          color: #999;
          font-size: 12px;
          margin-right: 4px;
          font-weight: normal;
        }

        .index-name {
          color: #666;
          margin-right: 4px;
        }

        .operator {
          color: #1890ff;
          margin-right: 4px;
          font-weight: 500;
        }

        .threshold {
          color: #333;
          font-weight: 500;
        }
      }
    }
  }
}

// 动画效果
@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式布局
@media (max-width: 1500px) {
  .rule-config-container {
    .search-card {
      .search-form-wrapper {
        .search-form {
          .form-row {
            .form-item {
              margin-right: 12px;

              /deep/ .ant-input,
              /deep/ .ant-select {
                width: 180px !important;
              }
            }
          }
        }
      }
    }
  }
}

@media (max-width: 1200px) {
  .rule-config-container {
    .search-card {
      .search-form-wrapper {
        .search-form {
          .form-row {
            .form-item {
              margin-right: 10px;

              /deep/ .ant-input,
              /deep/ .ant-select {
                width: 160px !important;
              }
            }
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .rule-config-container {
    padding: 16px;

    .search-card {
      .search-form-wrapper {
        .search-form {
          .form-row {
            flex-direction: column;
            align-items: stretch;

            .form-item {
              margin-right: 0;
              margin-bottom: 12px;
              width: 100%;

              /deep/ .ant-input,
              /deep/ .ant-select {
                width: 100% !important;
              }

              &.action-buttons {
                flex-direction: row;
                justify-content: flex-start;

                .ant-btn {
                  margin-right: 8px;
                  margin-left: 0 !important;
                }

                .expand-btn {
                  margin-left: auto !important;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
